package com.cl.erp.util;

import com.cl.erp.entity.AuthUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtils {
    @Value("${jwt.secret:qwer}")
    private  String secret;

    @Value("${jwt.expiration:3600}")
    private Long expiration;

//    @Value("${jwt.token}")
//    private String tokenHeader;

    public String generateToken(AuthUser authUser) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, authUser.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        LocalDateTime createdDate = LocalDateTime.now();
        LocalDateTime expirationDate = calculateExpirationDate(createdDate);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(Date.from(createdDate.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date.from(expirationDate.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    private LocalDateTime calculateExpirationDate(LocalDateTime createdDate) {
        return createdDate.plusSeconds(expiration);
    }

    public Boolean validateToken(String token, AuthUser authUser) {
        final String username = getUsernameFromToken(token);
        return (username.equals(authUser.getUsername())
                && !isTokenExpired(token)
        );
    }
    public Boolean validateToken(String token) {
        AuthUser authUser = SecurityUtils.getUser();
        return validateToken(token,authUser);
    }

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        Date expiration = getExpirationDateFromToken(token);
        LocalDateTime expirationLDT = LocalDateTime.ofInstant(expiration.toInstant(), ZoneId.systemDefault());
        return expirationLDT.isBefore(LocalDateTime.now());
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

}
